/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ListView,
  ScrollView,
  TextInput,
  Image,
  PixelRatio,
  BackHandler,
  Platform,
  Dimensions,
  Clipboard,
  DeviceEventEmitter,
  UIManager,
  LayoutAnimation,
  StatusBar,
  TouchableHighlight,
} from 'react-native';

import SearchList from './searchList';
import Common from '../../component/common';
import Loading from '../../component/loading';
import LoadError from '../../component/loadError';
import ScreenUtils from '../../component/ScreenUtils';

import ColumnSearch from './columnSearch';
import InfoSearch from './infoSearch';

import Detail from '../home/detail';
import Article from '../home/article';
import BriefIntroduction from '../specialColumn/briefIntroduction';
import ColumnDetails from '../specialColumn/columnDetails';


const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 20;

const pheight= Dimensions.get('window').height;
const totalWidth = Dimensions.get('window').width;
const HEADER_HEIGHT = totalWidth*0.112;
const os = Platform.OS;

export default class search extends Component {
  constructor(props) {
    super(props);
    var timer2;
    this.state = {
      checkDevice: '',
    	dataSource: new ListView.DataSource({
        	rowHasChanged: (row1, row2) => row1 !== row2,
      	}),
      dataSourceLength: this.props.name?this.props.name.length:0,
		loading: false,
      	success: true,
      	userInput: '',
      	errorMessage: '',
      	startLoadData:false,
    };
    this.fetchData = this.fetchData.bind(this); 
  }
  componentWillMount() {
    this.setState({
      dataSource: this.props.name?this.state.dataSource.cloneWithRows(this.props.name):this.state.dataSource.cloneWithRows([]),
    })
    Common.checkDevice((checkDevice) => {
      this.setState({checkDevice});
    });
    if (Platform.OS === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }  
  }  
  
  componentWillUnmount() { 
  	this.timer2 && clearTimeout(this.timer2);
    // this.dealForward.remove();
    if (Platform.OS === 'android') {  
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }  
  } 
  componentDidMount() {
  	// this.dealForward=this.props.navigator.navigationContext.addListener('didfocus',(newRouter)=>{
   //    this.fetchData();
   //    this.dealForward.remove();
   //  })
    this._setClipboardContent();
    
  }
  fetchData() {
  	let formData = new FormData();
    Common.fetchData("post", "/search/hotKeywords", formData, (responseData) => {
    	
    		this.setState({
				dataSource: this.state.dataSource.cloneWithRows(responseData.list),
				dataSourceLength:responseData.list.length,
				loading: false,
				success: true,
			  })
	   
    	
    },() => {
      this.setState({
		loading: false,
		success: false,
		errorMessage: "请求失败",
	  })
    },() => {
	    this.setState({
			loading: false,
			success: false,
			errorMessage: "网络错误",
		});
    });
  }
  onSearch() {
  	this.setState({
		startLoadData:true,
	})
  	DeviceEventEmitter.emit('searchData',null);
  } 
  _cancel() {
  	Common.onBack(this);
  }
  async _setClipboardContent() {
	try {
		var content =await Clipboard.getString();
		Clipboard.setString(content);
	} catch(e) {
		this.setState({ content: e.message });
	}
  }
  linking(val) {
    if(Platform.OS == 'ios'){
      NativeModules.JsAndroid.openUrl(val.url);
    }else{
      // Common.onForward(this, Article, val, 5);
      Common.onForward(this,Article,val,5);
    }
  }
  onPressLim(data,type,id,title,url){
 	switch (parseInt(type)){
 	    case 1:
 			//综艺 details
 			if(id){
 				Common.onForward(this,Detail,type,id);
 			}else{
 				this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 			break;
 		case 2:
 			//电影 details
 			if(id){
 				Common.onForward(this,Detail,type,id);
 			}else{
 				this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 			break;
 		case 3:
 			//电视剧 details
 			if(id){
 				Common.onForward(this,Detail,type,id);
 			}else{
 				this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 			break;
		case 4:
 			//资讯(话题包) details
 			if(id){
 				Common.onForward(this,Detail,type,id);
 			}else{
 				this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 			break;
 		case 5:
 			//资讯 details
 			if(id){
        this.linking({title:title,url:url,id:id})
 				// Common.onForward(this,Article,title,url,id);
 				//Common.onForward(this,Detail,"",id);
 			}else{
 				this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 			break;
 		case 8:
 			//专栏
 			if(id){
 				Common.onForward(this, BriefIntroduction, "", id)
 			}else{
	 			this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 			break;
 		case 9:
 			if(id){
 				Common.onForward(this, ColumnDetails,title, id);
 			}else{
	 			this.setState({
	 				userInput: data,
				  	startLoadData:true,
				});
 			}
 		default:
 			this.setState({
 				userInput: data,
			  	startLoadData:true,
			});
 			break;
 	}
 }
  renderHeader() {
  	return (
  		<View style={styles.container}>
        <View style={{flex: 1, justifyContent: 'center',alignItems: 'center', height:this.state.checkDevice == 'x'?(totalWidth*0.08+HEADER_HEIGHT):(STATUS_BAR_HEIGHT+HEADER_HEIGHT),backgroundColor: '#ff4546'}}>
          <View style={{height: this.state.checkDevice == 'x'?totalWidth*0.08:STATUS_BAR_HEIGHT}}/>
          <View style={{flex: 1,flexDirection: 'row',justifyContent: 'space-between'}}>
    			<View style={styles.searchContent}>
    				<Image style={styles.searchIcon} source = {require('../../images/search.png')}/>
  	  			<TextInput 
  		  			style={styles.searchBox} 
  		  			placeholder="搜索关键词"
  		  			underlineColorAndroid = "transparent"
  		  			placeholderTextColor = "#d3d3d3"
  		  			keyboardType = "web-search"       
  		  			multiline={false}
  		  			onChangeText={(userInput) => {
  		  					this.setState({userInput:userInput})
  		  					this.state.userInput==="" ? this.setState({startLoadData:false}) : null
  		  			    }
  		  			}
  	      			value ={this.state.userInput}
  	      			returnKeyType="search"
                returnKeyLabel="search"
  	      			onSubmitEditing = {this.onSearch.bind(this)}
  	      			ref="searchButton"
  	      			onFocus ={this._setClipboardContent.bind(this)}
  	  			/>
            </View>
  			 	<TouchableOpacity
  			 		style={styles.cancel}
  			 		onPress = {this._cancel.bind(this)}
  			 		activeOpacity ={0.7}
  			 	>
  			 		<Text style={styles.cancelText}>取消</Text>
  			    </TouchableOpacity>
    			
          </View>
        </View>
  		</View>	
  	)
  }

renderDefalutSearchList(hot) {
    let that = this;
    /*var pattern = /^[\u4E00-\u9FA5]{1,6}$/;*/ 
    var EPattern =/^[A-Za-z]{1,15}$/;
    /*alert("乡村如何留住乡愁:"+pattern.test('乡村"留住"'));*/
    let dealWidth = (Dimensions.get('window').width-ScreenUtils.scaleSize(40)*2)/2-ScreenUtils.scaleSize(84)-ScreenUtils.scaleSize(10);
    return (
      <TouchableHighlight 
        underlayColor="#fafafa" 
        delayPressIn={100}
        style={styles.defalutSearch}
        onPress ={ this.onPressLim.bind(this,hot.keyword,hot.type,hot.entityId||null,hot.keyword,hot.url)}
      >
        <View style={{flex:1,flexDirection:"row"}}>
          {
            !hot.type ? <Text style={styles.title}>{hot.keyword.trim()}</Text> :
            hot.keyword.trim().length <= 7 ?
              <Text style={styles.title}>{hot.keyword.trim()}</Text> :
                EPattern.test(hot.keyword.trim()) ?
                <Text style={styles.title}>{hot.keyword.trim()}</Text>:
                <Text 
                  style={[styles.title,{width:dealWidth}]}
                  
                >
                  {hot.keyword.trim()}
                </Text>
                
          }
          {
            hot.type === "8"?
              <Text style={styles.column}>专栏</Text>:null
          }
        </View>  
      </TouchableHighlight>
    )
  }

  renderDefault() {
  	return (
  		<View style={styles.content}>
  			<View style={styles.contentHeader}  >
  				<Text style={styles.hotSearch}>热门搜索</Text>
  			</View>
  			{
  				this.state.dataSourceLength>0?
  					<ListView
  						dataSource={this.state.dataSource}
  						renderRow={this.renderDefalutSearchList.bind(this)}
  						contentContainerStyle={styles.listView}
  						enableEmptySections={true}
  						keyboardShouldPersistTaps="always"
              initialListSize={0}
              pageSize={12}
  						removeClippedSubviews={ Platform.OS === 'android' ? true : false}
  					/> : 
  					<View style={styles.defalutEmptySearch}>
  						<Text>暂无推荐</Text>
  					</View>
  			}
  			
  		</View>
  	)
  }
  
  
 _onStartShouldSetResponderCapture(e){
 	const target = e.nativeEvent.target;
　　 this.refs.searchButton.blur();
 }
  
  render(){
    
  	return(
  		<View style={styles.mainWrap}>
  			{this.renderHeader()}
  			<ScrollView
  				showsVerticalScrollIndicator ={false}
  				horizontal = {false}
  				keyboardShouldPersistTaps="always"
  				keyboardDismissMode='interactive'
          removeClippedSubviews={ Platform.OS === 'android' ? true : false}
  			>
  				<View onStartShouldSetResponderCapture={this._onStartShouldSetResponderCapture.bind(this)}>
  					{
  						this.state.loading ?
  							<Loading style={{marginTop:pheight/2-60}}/>
  							: (
  								this.state.success ?
  									(
  										(this.state.userInput!="" && this.state.startLoadData) ?
  											<SearchList  keyValue = {this} startLoadData={this.state.startLoadData} keyWords={this.state.userInput}/>
  											: this.renderDefault()
  									)
  								  	: <LoadError style={{marginTop:pheight/2-60}} reload={this.fetchData} reason={this.state.errorMessage}/>
  							)				
  					}
  				</View>
  			</ScrollView> 
		</View>
  	)
  }
  
}

const styles = StyleSheet.create({
  mainWrap: {
  	flexDirection:'column',
  	backgroundColor:'#f7f7f7',
  	flex:1,	
  },
  contentWrap: {
  	flex:1,	
  },
  container: {
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(30),
  	backgroundColor:"#ff4545",
  	flexDirection:'row',
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:'#ff4545',
  	borderStyle:'solid',
  },
  searchContent:{
    width: ScreenUtils.scaleSize(578),
    height: ScreenUtils.scaleSize(51),
    marginHorizontal: totalWidth*0.035,
    marginVertical: ScreenUtils.scaleSize(20),
  	flexDirection:'row',
  	alignItems:"center",
    justifyContent: 'space-between',
    backgroundColor:"#fff",
    borderRadius:totalWidth*0.042,
    paddingLeft:ScreenUtils.scaleSize(20),
    
  },
  searchBox: {
  	flex:1,
    paddingVertical: 0,
    marginLeft: 5,
    fontSize:ScreenUtils.scaleSize(24),
  },
  searchIconWrap:{
    width: ScreenUtils.scaleSize(26),
  	height: ScreenUtils.scaleSize(26),
  },
  searchIcon:{
  	width:ScreenUtils.scaleSize(28),
  	height:ScreenUtils.scaleSize(28),
    resizeMode: 'contain',
  },
  cancel: {
  	width:ScreenUtils.scaleSize(90),
    height:totalWidth*0.084,
  	alignSelf:"center",
  	justifyContent:'center',
  },
  cancelText: {
  	color:'#fff',
  	textAlign:"center",
  	fontSize:ScreenUtils.scaleSize(28),
  },
 content: {
  	paddingLeft:ScreenUtils.scaleSize(40),
  	paddingRight:ScreenUtils.scaleSize(40),
  	backgroundColor:'#fff',  
  	borderBottomWidth:1,
  	borderColor:'#ececec',
  },
  contentHeader: {
  	height:ScreenUtils.scaleSize(100),
  	justifyContent:'center',
  },
  listView:{
  	width:Dimensions.get('window').width-ScreenUtils.scaleSize(40)*2,
  	flexDirection:"row",
  	flexWrap:"wrap",
  	alignItems:'flex-start',
  },
  hotSearch: {
  	color:'#a1a1a1',
  	fontSize:ScreenUtils.scaleSize(28),
  },
  defalutSearch: {
  	width:(Dimensions.get('window').width-ScreenUtils.scaleSize(40)*2)/2,
  	height:ScreenUtils.scaleSize(110),
  	flexDirection:'row',
  	alignItems:'center',
  	borderTopWidth:1/PixelRatio.get(),
  	borderColor:'rgb(243,243,243)', 
  },
  defalutEmptySearch:{
  	width:Dimensions.get('window').width-ScreenUtils.scaleSize(40)*2,
  	height:ScreenUtils.scaleSize(110)*5,
  	flexDirection:'row',
  	alignItems:'center',
  	justifyContent:"center",
  	borderTopWidth:1/PixelRatio.get(),
  	borderColor:'#f3f3f3', 
  },
  title: {
  	color:'#000',
  	fontSize:ScreenUtils.scaleSize(30),
  	paddingLeft:ScreenUtils.scaleSize(20),
  },
  column: {
  	marginLeft:ScreenUtils.scaleSize(10),
  	color:'#fe4445',
  	borderWidth:1,
  	borderStyle:'solid',
  	borderColor:'#fe4543',
  	borderRadius:ScreenUtils.scaleSize(36)/2,
  	fontSize:ScreenUtils.scaleSize(28),
  	width:ScreenUtils.scaleSize(84),
  	textAlign:'center',
  	height:ScreenUtils.scaleSize(36),
  },
});